package cn.com.eado.crm.m.net;

import android.util.Log;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.com.eado.crm.app.MyApp;
import cn.com.eado.crm.app.utils.LogUtil;
import cn.com.eado.crm.app.utils.SpUtil;
import cn.com.eado.crm.model.net.HttpApi;
import cn.com.eado.crm.model.net.LiveDataCallAdapterFactory;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class MyRetrofit {
    private static MyRetrofit instance;
    private HttpApi api;
    public static final String BASE_URL = "http://192.168.1.130:8020";//"http://121.201.108.27:8008";

    public static MyRetrofit getInstance(){
        if (instance == null){
            synchronized (MyRetrofit.class){
                if (instance == null) {
                    instance = new MyRetrofit();
                }
            }
        }
        return instance;
    }

    private MyRetrofit(){
        init();
    }

    public HttpApi getApi(){
        return api;
    }

    public void reset() {
        instance = null;
    }

    //init
    private void init() {
        OkHttpClient client = getClient();
        Retrofit retrofit = getRetrofit(client);
        api = retrofit.create(HttpApi.class);
    }

    private OkHttpClient getClient(){
        return new OkHttpClient.Builder()
                .addInterceptor(new addCookiesInterceptor())
                .addInterceptor(new getCookiesInterceptor())
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .connectTimeout(10, TimeUnit.SECONDS)
                .build();
    }

    private Retrofit getRetrofit(OkHttpClient client){
        LogUtil.e("tag", "base_url = " + SpUtil.readString(MyApp.instance, "base_url", BASE_URL));
        return new Retrofit.Builder()
                .client(client)
                .addConverterFactory(ScalarsConverterFactory.create())
//                .addConverterFactory(GsonConverterFactory.create())
                .addConverterFactory(LenientGsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addCallAdapterFactory(new LiveDataCallAdapterFactory())
                .baseUrl(SpUtil.readString(MyApp.instance, "base_url", BASE_URL))
                .build();
    }

    private HashSet<String> cookies   = new HashSet<>();
    public class getCookiesInterceptor implements Interceptor {
        private List<String> headers;
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            okhttp3.Response originalResponse = chain.proceed(chain.request());

//            if (!originalResponse.headers("Set-Cookie").isEmpty()) {
//
//
//                for (String header : originalResponse.headers("Set-Cookie")) {
//                    cookies.add(header);
//                }
//            }
//            return originalResponse;

            headers = originalResponse.headers("Set-Cookie");
            if (!headers.isEmpty()) {
                for (String header : originalResponse.headers("Set-Cookie")) {
                    cookies.add(header);
                }
            }
            return originalResponse;
        }
    }

    public class addCookiesInterceptor implements Interceptor {

        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request.Builder builder = chain.request().newBuilder();

            for (String cookie : cookies) {
                builder.addHeader("Cookie", cookie);
                Log.v("OkHttp", "Adding Header: " + cookie); // This is done so I know which headers are being added; this interceptor is used after the normal logging of OkHttp
            }

            return chain.proceed(builder.build());
        }
    }
}
